package com.tz.online.order.action;

import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tz.online.entity.Address;
import com.tz.online.entity.Cart;
import com.tz.online.entity.Order;
import com.tz.online.entity.OrderItem;
import com.tz.online.entity.User;
import com.tz.online.order.service.IOrderService;
import com.tz.online.util.BeanFactory;

/**
 * 接收提交订单请求
 * @author Administrator
 *
 */
@WebServlet(name="saveOrder",urlPatterns="/permission/order/saveOrder")
public class SaveOrderAction extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1124957441201065238L;
	IOrderService os = (IOrderService)BeanFactory.getBean("orderService");
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//接收地址ID
		String addressId = req.getParameter("addressId");
		String bids = req.getParameter("bids");
		String[] arr = bids.split(":");
		//获得地址对象
		Address a = os.queryAddressById(addressId);
		Order o = new Order();
		User user = (User) req.getSession().getAttribute("userInfo");
		Cart cart = (Cart) req.getSession().getAttribute("cart");
		Set<OrderItem> items = cart.getItems();
		Set<OrderItem> selectItem = new HashSet<OrderItem>();
		
		int count = 0;
		double allPrice = 0.0;
		for(OrderItem oi :items){
			for(String id:arr){
				if(oi.getBook().getBookId().toString().equals(id)){
					selectItem.add(oi);
					count += oi.getCount();
					allPrice += oi.getAllPrice();
				}	
			}
		}
		
		items.removeAll(selectItem);
		cart.setAllcount(cart.getAllcount() - count);
		cart.setAllPrice(cart.getAllPrice() - allPrice);
		
		req.getSession().setAttribute("cart", cart);
		
		o.setItems(selectItem);
		o.setAddress(a);
		o.setCreateDate(new Date());
		o.setOrderNum("TZ"+new Date().getTime());
		o.setUser(user);
		o.setOrderStatus("0");
		
		os.saveOrder(o);
		
		resp.sendRedirect(req.getContextPath()+"/permission/order/list");
		//重定向到查询订单列表页面
	//save(o);
		
	}
}
